
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>8. Compound statements &#8212; Python 3.8.13 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" href="../_static/pydoctheme.css?2022.1" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script src="../_static/jquery.js"></script>
    <script src="../_static/underscore.js"></script>
    <script src="../_static/doctools.js"></script>
    <script src="../_static/language_data.js"></script>
    
    <script src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.8.13 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9. Top-level components" href="toplevel_components.html" />
    <link rel="prev" title="7. Simple statements" href="simple_stmts.html" />
    <link rel="canonical" href="https://docs.python.org/3/reference/compound_stmts.html" />
    
      
    

    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
            <script type="text/javascript" src="../_static/copybutton.js"></script>
            <script type="text/javascript" src="../_static/menu.js"></script> 

  </head>
<body>
<div class="mobile-nav">
    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
    <label for="menuToggler" class="toggler__label">
        <span></span>
    </label>
    <nav class="nav-content" role="navigation">
         <a href="https://www.python.org/" class="nav-logo">
             <img src="../_static/py.svg" alt="Logo"/>
         </a>
        <div class="version_switcher_placeholder"></div>
        <form role="search" class="search" action="../search.html" method="get">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
                <path fill-rule="nonzero"
                        d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" fill="#444"></path>
            </svg>
            <input type="text" name="q" aria-label="Quick search"/>
            <input type="submit" value="Go"/>
        </form>
    </nav>
    <div class="menu-wrapper">
        <nav class="menu" role="navigation" aria-label="main navigation">
            <div class="language_switcher_placeholder"></div>
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8. Compound statements</a><ul>
<li><a class="reference internal" href="#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li><a class="reference internal" href="#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li><a class="reference internal" href="#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li><a class="reference internal" href="#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#function-definitions">8.6. Function definitions</a></li>
<li><a class="reference internal" href="#class-definitions">8.7. Class definitions</a></li>
<li><a class="reference internal" href="#coroutines">8.8. Coroutines</a><ul>
<li><a class="reference internal" href="#coroutine-function-definition">8.8.1. Coroutine function definition</a></li>
<li><a class="reference internal" href="#the-async-for-statement">8.8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-async-with-statement">8.8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="simple_stmts.html"
                        title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="toplevel_components.html"
                        title="next chapter"><span class="section-number">9. </span>Top-level components</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.8/Doc/reference/compound_stmts.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </nav>
    </div>
</div>

  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="9. Top-level components"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="7. Simple statements"
             accesskey="P">previous</a> |</li>

          <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.8.13 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
                     |
                </li>
            
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="compound-statements">
<span id="compound"></span><h1><span class="section-number">8. </span>Compound statements<a class="headerlink" href="#compound-statements" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way.  In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.</p>
<p>The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> and <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements implement
traditional control flow constructs.  <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> specifies exception
handlers and/or cleanup code for a group of statements, while the
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows the execution of initialization and
finalization code around a block of code.  Function and class definitions are
also syntactically compound statements.</p>
<p id="index-1">A compound statement consists of one or more ‘clauses.’  A clause consists of a
header and a ‘suite.’  The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon.  A suite is a group of statements
controlled by a clause.  A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header’s colon, or it
can be one or more indented statements on subsequent lines.  Only the latter
form of a suite can contain nested compound statements; the following is illegal,
mostly because it wouldn’t be clear to which <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause a following
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause would belong:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">test1</span><span class="p">:</span> <span class="k">if</span> <span class="n">test2</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> calls are
executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="o">&lt;</span> <span class="n">z</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">y</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
</pre></div>
</div>
<p>Summarizing:</p>
<pre>
<strong id="grammar-token-compound-stmt">compound_stmt</strong> ::=  <a class="reference internal" href="#grammar-token-if-stmt"><code class="xref docutils literal notranslate"><span class="pre">if_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-while-stmt"><code class="xref docutils literal notranslate"><span class="pre">while_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-try-stmt"><code class="xref docutils literal notranslate"><span class="pre">try_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a>
                   | <a class="reference internal" href="#grammar-token-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a>
                   | <a class="reference internal" href="#grammar-token-async-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">async_with_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-async-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">async_for_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-async-funcdef"><code class="xref docutils literal notranslate"><span class="pre">async_funcdef</span></code></a>
<strong id="grammar-token-suite">suite        </strong> ::=  <a class="reference internal" href="#grammar-token-stmt-list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>+ DEDENT
<strong id="grammar-token-statement">statement    </strong> ::=  <a class="reference internal" href="#grammar-token-stmt-list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | <a class="reference internal" href="#grammar-token-compound-stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a>
<strong id="grammar-token-stmt-list">stmt_list    </strong> ::=  <a class="reference internal" href="simple_stmts.html#grammar-token-simple-stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a> (&quot;;&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-simple-stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a>)* [&quot;;&quot;]
</pre>
<p id="index-2">Note that statements always end in a <code class="docutils literal notranslate"><span class="pre">NEWLINE</span></code> possibly followed by a
<code class="docutils literal notranslate"><span class="pre">DEDENT</span></code>.  Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
‘dangling <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>’ problem is solved in Python by requiring nested
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements to be indented).</p>
<p>The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.</p>
<div class="section" id="the-if-statement">
<span id="else"></span><span id="elif"></span><span id="if"></span><h2><span class="section-number">8.1. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement<a class="headerlink" href="#the-if-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-3">The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is used for conditional execution:</p>
<pre>
<strong id="grammar-token-if-stmt">if_stmt</strong> ::=  &quot;if&quot; <a class="reference internal" href="expressions.html#grammar-token-assignment-expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
             (&quot;elif&quot; <a class="reference internal" href="expressions.html#grammar-token-assignment-expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)*
             [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section <a class="reference internal" href="expressions.html#booleans"><span class="std std-ref">Boolean operations</span></a> for the definition of
true and false); then that suite is executed (and no other part of the
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is executed or evaluated).  If all expressions are
false, the suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed.</p>
</div>
<div class="section" id="the-while-statement">
<span id="while"></span><h2><span class="section-number">8.2. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement<a class="headerlink" href="#the-while-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-4">The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement is used for repeated execution as long as an
expression is true:</p>
<pre>
<strong id="grammar-token-while-stmt">while_stmt</strong> ::=  &quot;while&quot; <a class="reference internal" href="expressions.html#grammar-token-assignment-expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
                [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed and the loop
terminates.</p>
<p id="index-5">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause’s suite.  A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.</p>
</div>
<div class="section" id="the-for-statement">
<span id="for"></span><h2><span class="section-number">8.3. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement<a class="headerlink" href="#the-for-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-6">The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:</p>
<pre>
<strong id="grammar-token-for-stmt">for_stmt</strong> ::=  &quot;for&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target-list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;in&quot; <a class="reference internal" href="expressions.html#grammar-token-expression-list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
              [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>The expression list is evaluated once; it should yield an iterable object.  An
iterator is created for the result of the <code class="docutils literal notranslate"><span class="pre">expression_list</span></code>.  The suite is
then executed once for each item provided by the iterator, in the order returned
by the iterator.  Each item in turn is assigned to the target list using the
standard rules for assignments (see <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">Assignment statements</span></a>), and then the suite is
executed.  When the items are exhausted (which is immediately when the sequence
is empty or an iterator raises a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception), the suite in
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed, and the loop terminates.</p>
<p id="index-7">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause’s suite.  A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause if there is no next
item.</p>
<p>The for-loop makes assignments to the variables in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">5</span>             <span class="c1"># this will not affect the for-loop</span>
                      <span class="c1"># because i will be overwritten with the next</span>
                      <span class="c1"># index in the range</span>
</pre></div>
</div>
<p id="index-8">Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, they will not have been assigned to at all by the loop.  Hint:
the built-in function <a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> returns an iterator of integers suitable to
emulate the effect of Pascal’s <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">:=</span> <span class="pre">a</span> <span class="pre">to</span> <span class="pre">b</span> <span class="pre">do</span></code>; e.g., <code class="docutils literal notranslate"><span class="pre">list(range(3))</span></code>
returns the list <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">2]</span></code>.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p id="index-9">There is a subtlety when the sequence is being modified by the loop (this can
only occur for mutable sequences, e.g. lists).  An internal counter is used
to keep track of which item is used next, and this is incremented on each
iteration.  When this counter has reached the length of the sequence the loop
terminates.  This means that if the suite deletes the current (or a previous)
item from the sequence, the next item will be skipped (since it gets the
index of the current item which has already been treated).  Likewise, if the
suite inserts an item in the sequence before the current item, the current
item will be treated again the next time through the loop. This can lead to
nasty bugs that can be avoided by making a temporary copy using a slice of
the whole sequence, e.g.,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">[:]:</span>
    <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-try-statement">
<span id="finally"></span><span id="except"></span><span id="try"></span><h2><span class="section-number">8.4. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement<a class="headerlink" href="#the-try-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-10">The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement specifies exception handlers and/or cleanup code
for a group of statements:</p>
<pre>
<strong id="grammar-token-try-stmt">try_stmt </strong> ::=  <a class="reference internal" href="#grammar-token-try1-stmt"><code class="xref docutils literal notranslate"><span class="pre">try1_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-try2-stmt"><code class="xref docutils literal notranslate"><span class="pre">try2_stmt</span></code></a>
<strong id="grammar-token-try1-stmt">try1_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
               (&quot;except&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;as&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
               [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
               [&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
<strong id="grammar-token-try2-stmt">try2_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
               &quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<p>The <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause(s) specify one or more exception handlers. When no
exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, no exception handler is executed.
When an exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> suite, a search for an exception
handler is started.  This search inspects the except clauses in turn until one
is found that matches the exception.  An expression-less except clause, if
present, must be last; it matches any exception.  For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is “compatible” with the exception.  An object is
compatible with an exception if it is the class or a base class of the exception
object, or a tuple containing an item that is the class or a base class of
the exception object.</p>
<p>If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack.  <a class="footnote-reference brackets" href="#id4" id="id1">1</a></p>
<p>If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement raised the exception).</p>
<p id="index-11">When a matching except clause is found, the exception is assigned to the target
specified after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> keyword in that except clause, if present, and
the except clause’s suite is executed.  All except clauses must have an
executable block.  When the end of this block is reached, execution continues
normally after the entire try statement.  (This means that if two nested
handlers exist for the same exception, and the exception occurs in the try
clause of the inner handler, the outer handler will not handle the exception.)</p>
<p>When an exception has been assigned using <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">target</span></code>, it is cleared at the
end of the except clause.  This is as if</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
    <span class="n">foo</span>
</pre></div>
</div>
<p>was translated to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">foo</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">N</span>
</pre></div>
</div>
<p>This means the exception must be assigned to a different name to be able to
refer to it after the except clause.  Exceptions are cleared because with the
traceback attached to them, they form a reference cycle with the stack frame,
keeping all locals in that frame alive until the next garbage collection occurs.</p>
<p id="index-12">Before an except clause’s suite is executed, details about the exception are
stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module and can be accessed via <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> returns a 3-tuple consisting of the exception class, the
exception instance and a traceback object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) identifying
the point in the program where the exception occurred.  <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
values are restored to their previous values (before the call) when returning
from a function that handled an exception.</p>
<p id="index-13">The optional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is executed if the control flow leaves the
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>,
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>, or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement was executed.  Exceptions in
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause are not handled by the preceding <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
clauses.</p>
<p id="index-14">If <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> is present, it specifies a ‘cleanup’ handler.  The
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause is executed, including any <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause
is executed.  If there is a saved exception it is re-raised at the end of the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause.  If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause raises another
exception, the saved exception is set as the context of the new exception.
If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>
or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement, the saved exception is discarded:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">42</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The exception information is not available to the program during execution of
the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p>
<p id="index-15">When a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is
executed in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite of a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>…<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
statement, the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is also executed ‘on the way out.’</p>
<p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
statement executed.  Since the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause always executes, a
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement executed in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will
always be the last one executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;try&#39;</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;finally&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="go">&#39;finally&#39;</span>
</pre></div>
</div>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>,
and information on using the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement to generate exceptions
may be found in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.8: </span>Prior to Python 3.8, a <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement was illegal in the
<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause due to a problem with the implementation.</p>
</div>
</div>
<div class="section" id="the-with-statement">
<span id="as"></span><span id="with"></span><h2><span class="section-number">8.5. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement<a class="headerlink" href="#the-with-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-16">The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is used to wrap the execution of a block with
methods defined by a context manager (see section <a class="reference internal" href="datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>).
This allows common <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
usage patterns to be encapsulated for convenient reuse.</p>
<pre>
<strong id="grammar-token-with-stmt">with_stmt</strong> ::=  &quot;with&quot; <a class="reference internal" href="#grammar-token-with-item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-with-item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a>)* &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-with-item">with_item</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;as&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>]
</pre>
<p>The execution of the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement with one “item” proceeds as follows:</p>
<ol class="arabic">
<li><p>The context expression (the expression given in the <a class="reference internal" href="#grammar-token-with-item"><code class="xref std std-token docutils literal notranslate"><span class="pre">with_item</span></code></a>) is
evaluated to obtain a context manager.</p></li>
<li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is loaded for later use.</p></li>
<li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is loaded for later use.</p></li>
<li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is invoked.</p></li>
<li><p>If a target was included in the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the return value
from <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is assigned to it.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>
method returns without an error, then <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> will always be
called. Thus, if an error occurs during the assignment to the target list,
it will be treated the same as an error occurring within the suite would
be. See step 6 below.</p>
</div>
</li>
<li><p>The suite is executed.</p></li>
<li><p>The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is invoked.  If an exception
caused the suite to be exited, its type, value, and traceback are passed as
arguments to <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>. Otherwise, three <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> arguments are
supplied.</p>
<p>If the suite was exited due to an exception, and the return value from the
<a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method was false, the exception is reraised.  If the return
value was true, the exception is suppressed, and execution continues with the
statement following the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>If the suite was exited for any reason other than an exception, the return
value from <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is ignored, and execution proceeds at the normal
location for the kind of exit that was taken.</p>
</li>
</ol>
<p>The following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">EXPRESSION</span> <span class="k">as</span> <span class="n">TARGET</span><span class="p">:</span>
    <span class="n">SUITE</span>
</pre></div>
</div>
<p>is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPRESSION</span><span class="p">)</span>
<span class="n">enter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__enter__</span>
<span class="n">exit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__exit__</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">enter</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span>
<span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span>
    <span class="n">SUITE</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span>
        <span class="k">raise</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span>
        <span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>With more than one item, the context managers are processed as if multiple
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements were nested:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
    <span class="n">SUITE</span>
</pre></div>
</div>
<p>is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
        <span class="n">SUITE</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.1: </span>Support for multiple context expressions.</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="function-definitions">
<span id="def"></span><span id="function"></span><span id="index-18"></span><h2><span class="section-number">8.6. </span>Function definitions<a class="headerlink" href="#function-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-19">A function definition defines a user-defined function object (see section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-funcdef">funcdef                  </strong> ::=  [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;def&quot; <a class="reference internal" href="#grammar-token-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-parameter-list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;)&quot;
                               [&quot;-&gt;&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-decorators">decorators               </strong> ::=  <a class="reference internal" href="#grammar-token-decorator"><code class="xref docutils literal notranslate"><span class="pre">decorator</span></code></a>+
<strong id="grammar-token-decorator">decorator                </strong> ::=  &quot;&#64;&quot; <a class="reference internal" href="#grammar-token-dotted-name"><code class="xref docutils literal notranslate"><span class="pre">dotted_name</span></code></a> [&quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-argument-list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [&quot;,&quot;]] &quot;)&quot;] NEWLINE
<strong id="grammar-token-dotted-name">dotted_name              </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;.&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
<strong id="grammar-token-parameter-list">parameter_list           </strong> ::=  <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* &quot;,&quot; &quot;/&quot; [&quot;,&quot; [<a class="reference internal" href="#grammar-token-parameter-list-no-posonly"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_no_posonly</span></code></a>]]
                                 | <a class="reference internal" href="#grammar-token-parameter-list-no-posonly"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_no_posonly</span></code></a>
<strong id="grammar-token-parameter-list-no-posonly">parameter_list_no_posonly</strong> ::=  <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [<a class="reference internal" href="#grammar-token-parameter-list-starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></a>]]
                               | <a class="reference internal" href="#grammar-token-parameter-list-starargs"><code class="xref docutils literal notranslate"><span class="pre">parameter_list_starargs</span></code></a>
<strong id="grammar-token-parameter-list-starargs">parameter_list_starargs  </strong> ::=  &quot;*&quot; [<a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a>] (&quot;,&quot; <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a>)* [&quot;,&quot; [&quot;**&quot; <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]]]
                               | &quot;**&quot; <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;,&quot;]
<strong id="grammar-token-parameter">parameter                </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;:&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-defparameter">defparameter             </strong> ::=  <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;=&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-funcname">funcname                 </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A function definition is an executable statement.  Its execution binds the
function name in the current local namespace to a function object (a wrapper
around the executable code for the function).  This function object contains a
reference to the current global namespace as the global namespace to be used
when the function is called.</p>
<p>The function definition does not execute the function body; this gets executed
only when the function is called. <a class="footnote-reference brackets" href="#id5" id="id2">2</a></p>
<p id="index-20">A function definition may be wrapped by one or more <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> expressions.
Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition.  The result must be a callable, which is
invoked with the function object as the only argument. The returned value is
bound to the function name instead of the function object.  Multiple decorators
are applied in nested fashion. For example, the following code</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@f2</span>
<span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
</pre></div>
</div>
<p>is roughly equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
<span class="n">func</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">func</span><span class="p">))</span>
</pre></div>
</div>
<p>except that the original function is not temporarily bound to the name <code class="docutils literal notranslate"><span class="pre">func</span></code>.</p>
<p id="index-21">When one or more <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> have the form <em>parameter</em> <code class="docutils literal notranslate"><span class="pre">=</span></code>
<em>expression</em>, the function is said to have “default parameter values.”  For a
parameter with a default value, the corresponding <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">argument</span></a> may be
omitted from a call, in which
case the parameter’s default value is substituted.  If a parameter has a default
value, all following parameters up until the “<code class="docutils literal notranslate"><span class="pre">*</span></code>” must also have a default
value — this is a syntactic restriction that is not expressed by the grammar.</p>
<p><strong>Default parameter values are evaluated from left to right when the function
definition is executed.</strong> This means that the expression is evaluated once, when
the function is defined, and that the same “pre-computed” value is used for each
call.  This is especially important to understand when a default parameter is a
mutable object, such as a list or a dictionary: if the function modifies the
object (e.g. by appending an item to a list), the default value is in effect
modified.  This is generally not what was intended.  A way around this is to use
<code class="docutils literal notranslate"><span class="pre">None</span></code> as the default, and explicitly test for it in the body of the function,
e.g.:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">whats_on_the_telly</span><span class="p">(</span><span class="n">penguin</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">penguin</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">penguin</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">penguin</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;property of the zoo&quot;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">penguin</span>
</pre></div>
</div>
<p id="index-22">Function call semantics are described in more detail in section <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>. A
function call always assigns values to all parameters mentioned in the parameter
list, either from positional arguments, from keyword arguments, or from default
values.  If the form “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” is present, it is initialized to a tuple
receiving any excess positional parameters, defaulting to the empty tuple.
If the form “<code class="docutils literal notranslate"><span class="pre">**identifier</span></code>” is present, it is initialized to a new
ordered mapping receiving any excess keyword arguments, defaulting to a
new empty mapping of the same type.  Parameters after “<code class="docutils literal notranslate"><span class="pre">*</span></code>” or
“<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” are keyword-only parameters and may only be passed
by keyword arguments.  Parameters before “<code class="docutils literal notranslate"><span class="pre">/</span></code>” are positional-only parameters
and may only be passed by positional arguments.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.8: </span>The <code class="docutils literal notranslate"><span class="pre">/</span></code> function parameter syntax may be used to indicate positional-only
parameters. See <span class="target" id="index-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0570"><strong>PEP 570</strong></a> for details.</p>
</div>
<p id="index-24">Parameters may have an <a class="reference internal" href="../glossary.html#term-function-annotation"><span class="xref std std-term">annotation</span></a> of the form “<code class="docutils literal notranslate"><span class="pre">:</span> <span class="pre">expression</span></code>”
following the parameter name.  Any parameter may have an annotation, even those of the form
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code>.  Functions may have “return” annotation of
the form “<code class="docutils literal notranslate"><span class="pre">-&gt;</span> <span class="pre">expression</span></code>” after the parameter list.  These annotations can be
any valid Python expression.  The presence of annotations does not change the
semantics of a function.  The annotation values are available as values of
a dictionary keyed by the parameters’ names in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>
attribute of the function object.  If the <code class="docutils literal notranslate"><span class="pre">annotations</span></code> import from
<a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> is used, annotations are preserved as strings at runtime which
enables postponed evaluation.  Otherwise, they are evaluated when the function
definition is executed.  In this case annotations may be evaluated in
a different order than they appear in the source code.</p>
<p id="index-25">It is also possible to create anonymous functions (functions not bound to a
name), for immediate use in expressions.  This uses lambda expressions, described in
section <a class="reference internal" href="expressions.html#lambda"><span class="std std-ref">Lambdas</span></a>.  Note that the lambda expression is merely a shorthand for a
simplified function definition; a function defined in a “<a class="reference internal" href="#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>”
statement can be passed around or assigned to another name just like a function
defined by a lambda expression.  The “<code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code>” form is actually more powerful
since it allows the execution of multiple statements and annotations.</p>
<p><strong>Programmer’s note:</strong> Functions are first-class objects.  A “<code class="docutils literal notranslate"><span class="pre">def</span></code>” statement
executed inside a function definition defines a local function that can be
returned or passed around.  Free variables used in the nested function can
access the local variables of the function containing the def.  See section
<a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for details.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-26"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3107"><strong>PEP 3107</strong></a> - Function Annotations</dt><dd><p>The original specification for function annotations.</p>
</dd>
<dt><span class="target" id="index-27"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0484"><strong>PEP 484</strong></a> - Type Hints</dt><dd><p>Definition of a standard meaning for annotations: type hints.</p>
</dd>
<dt><span class="target" id="index-28"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0526"><strong>PEP 526</strong></a> - Syntax for Variable Annotations</dt><dd><p>Ability to type hint variable declarations, including class
variables and instance variables</p>
</dd>
<dt><span class="target" id="index-29"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0563"><strong>PEP 563</strong></a> - Postponed Evaluation of Annotations</dt><dd><p>Support for forward references within annotations by preserving
annotations in a string form at runtime instead of eager evaluation.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="class-definitions">
<span id="class"></span><h2><span class="section-number">8.7. </span>Class definitions<a class="headerlink" href="#class-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-30">A class definition defines a class object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-classdef">classdef   </strong> ::=  [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;class&quot; <a class="reference internal" href="#grammar-token-classname"><code class="xref docutils literal notranslate"><span class="pre">classname</span></code></a> [<a class="reference internal" href="#grammar-token-inheritance"><code class="xref docutils literal notranslate"><span class="pre">inheritance</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-inheritance">inheritance</strong> ::=  &quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-argument-list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a>] &quot;)&quot;
<strong id="grammar-token-classname">classname  </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A class definition is an executable statement.  The inheritance list usually
gives a list of base classes (see <a class="reference internal" href="datamodel.html#metaclasses"><span class="std std-ref">Metaclasses</span></a> for more advanced uses), so
each item in the list should evaluate to a class object which allows
subclassing.  Classes without an inheritance list inherit, by default, from the
base class <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>; hence,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The class’s suite is then executed in a new execution frame (see <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a>),
using a newly created local namespace and the original global namespace.
(Usually, the suite contains mostly function definitions.)  When the class’s
suite finishes execution, its execution frame is discarded but its local
namespace is saved. <a class="footnote-reference brackets" href="#id6" id="id3">3</a> A class object is then created using the inheritance
list for the base classes and the saved local namespace for the attribute
dictionary.  The class name is bound to this class object in the original local
namespace.</p>
<p>The order in which attributes are defined in the class body is preserved
in the new class’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>.  Note that this is reliable only right
after the class is created and only for classes that were defined using
the definition syntax.</p>
<p>Class creation can be customized heavily using <a class="reference internal" href="datamodel.html#metaclasses"><span class="std std-ref">metaclasses</span></a>.</p>
<p id="index-31">Classes can also be decorated: just like when decorating functions,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@f2</span>
<span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
</pre></div>
</div>
<p>is roughly equivalent to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span> <span class="k">pass</span>
<span class="n">Foo</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">Foo</span><span class="p">))</span>
</pre></div>
</div>
<p>The evaluation rules for the decorator expressions are the same as for function
decorators.  The result is then bound to the class name.</p>
<p><strong>Programmer’s note:</strong> Variables defined in the class definition are class
attributes; they are shared by instances.  Instance attributes can be set in a
method with <code class="docutils literal notranslate"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code>.  Both class and instance attributes are
accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></code>”, and an instance attribute hides
a class attribute with the same name when accessed in this way.  Class
attributes can be used as defaults for instance attributes, but using mutable
values there can lead to unexpected results.  <a class="reference internal" href="datamodel.html#descriptors"><span class="std std-ref">Descriptors</span></a>
can be used to create instance variables with different implementation details.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-32"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3115"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt><dd><p>The proposal that changed the declaration of metaclasses to the current
syntax, and the semantics for how classes with metaclasses are
constructed.</p>
</dd>
<dt><span class="target" id="index-33"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3129"><strong>PEP 3129</strong></a> - Class Decorators</dt><dd><p>The proposal that added class decorators.  Function and method decorators
were introduced in <span class="target" id="index-34"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="coroutines">
<span id="async"></span><h2><span class="section-number">8.8. </span>Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.5.</span></p>
</div>
<div class="section" id="coroutine-function-definition">
<span id="async-def"></span><span id="index-35"></span><h3><span class="section-number">8.8.1. </span>Coroutine function definition<a class="headerlink" href="#coroutine-function-definition" title="Permalink to this headline">¶</a></h3>
<pre>
<strong id="grammar-token-async-funcdef">async_funcdef</strong> ::=  [<a class="reference internal" href="#grammar-token-decorators"><code class="xref docutils literal notranslate"><span class="pre">decorators</span></code></a>] &quot;async&quot; &quot;def&quot; <a class="reference internal" href="#grammar-token-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-parameter-list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;)&quot;
                   [&quot;-&gt;&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<p id="index-36">Execution of Python coroutines can be suspended and resumed at many points
(see <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a>).  Inside the body of a coroutine function, <code class="docutils literal notranslate"><span class="pre">await</span></code> and
<code class="docutils literal notranslate"><span class="pre">async</span></code> identifiers become reserved keywords; <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions,
<a class="reference internal" href="#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> and <a class="reference internal" href="#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> can only be used in
coroutine function bodies.</p>
<p>Functions defined with <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> syntax are always coroutine functions,
even if they do not contain <code class="docutils literal notranslate"><span class="pre">await</span></code> or <code class="docutils literal notranslate"><span class="pre">async</span></code> keywords.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use a <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> expression inside the body
of a coroutine function.</p>
<p>An example of a coroutine function:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">param1</span><span class="p">,</span> <span class="n">param2</span><span class="p">):</span>
    <span class="n">do_stuff</span><span class="p">()</span>
    <span class="k">await</span> <span class="n">some_coroutine</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="the-async-for-statement">
<span id="async-for"></span><span id="index-37"></span><h3><span class="section-number">8.8.2. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement<a class="headerlink" href="#the-async-for-statement" title="Permalink to this headline">¶</a></h3>
<pre>
<strong id="grammar-token-async-for-stmt">async_for_stmt</strong> ::=  &quot;async&quot; <a class="reference internal" href="#grammar-token-for-stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
</pre>
<p>An <a class="reference internal" href="../glossary.html#term-asynchronous-iterable"><span class="xref std std-term">asynchronous iterable</span></a> is able to call asynchronous code in its
<em>iter</em> implementation, and <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a> can call asynchronous
code in its <em>next</em> method.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement allows convenient iteration over asynchronous
iterators.</p>
<p>The following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">for</span> <span class="n">TARGET</span> <span class="ow">in</span> <span class="n">ITER</span><span class="p">:</span>
    <span class="n">SUITE</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">SUITE2</span>
</pre></div>
</div>
<p>Is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">ITER</span><span class="p">)</span>
<span class="nb">iter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__aiter__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span>
<span class="n">running</span> <span class="o">=</span> <span class="kc">True</span>

<span class="k">while</span> <span class="n">running</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">TARGET</span> <span class="o">=</span> <span class="k">await</span> <span class="nb">type</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span><span class="o">.</span><span class="fm">__anext__</span><span class="p">(</span><span class="nb">iter</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">StopAsyncIteration</span><span class="p">:</span>
        <span class="n">running</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">SUITE</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">SUITE2</span>
</pre></div>
</div>
<p>See also <a class="reference internal" href="datamodel.html#object.__aiter__" title="object.__aiter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aiter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__anext__" title="object.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__anext__()</span></code></a> for details.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement outside the
body of a coroutine function.</p>
</div>
<div class="section" id="the-async-with-statement">
<span id="async-with"></span><span id="index-38"></span><h3><span class="section-number">8.8.3. </span>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement<a class="headerlink" href="#the-async-with-statement" title="Permalink to this headline">¶</a></h3>
<pre>
<strong id="grammar-token-async-with-stmt">async_with_stmt</strong> ::=  &quot;async&quot; <a class="reference internal" href="#grammar-token-with-stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
</pre>
<p>An <a class="reference internal" href="../glossary.html#term-asynchronous-context-manager"><span class="xref std std-term">asynchronous context manager</span></a> is a <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> that is
able to suspend execution in its <em>enter</em> and <em>exit</em> methods.</p>
<p>The following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">with</span> <span class="n">EXPRESSION</span> <span class="k">as</span> <span class="n">TARGET</span><span class="p">:</span>
    <span class="n">SUITE</span>
</pre></div>
</div>
<p>is semantically equivalent to:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPRESSION</span><span class="p">)</span>
<span class="n">aexit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__aexit__</span>
<span class="n">aenter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__aenter__</span>
<span class="n">value</span> <span class="o">=</span> <span class="k">await</span> <span class="n">aenter</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span>
<span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span>
    <span class="n">SUITE</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span>
        <span class="k">raise</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span>
        <span class="k">await</span> <span class="n">aexit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>See also <a class="reference internal" href="datamodel.html#object.__aenter__" title="object.__aenter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aenter__()</span></code></a> and <a class="reference internal" href="datamodel.html#object.__aexit__" title="object.__aexit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aexit__()</span></code></a> for details.</p>
<p>It is a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> to use an <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement outside the
body of a coroutine function.</p>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<dl class="simple">
<dt><span class="target" id="index-39"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0492"><strong>PEP 492</strong></a> - Coroutines with async and await syntax</dt><dd><p>The proposal that made coroutines a proper standalone concept in Python,
and added supporting syntax.</p>
</dd>
</dl>
</div>
<p class="rubric">Footnotes</p>
<dl class="footnote brackets">
<dt class="label" id="id4"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
<dd><p>The exception is propagated to the invocation stack unless
there is a <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause which happens to raise another
exception. That new exception causes the old one to be lost.</p>
</dd>
<dt class="label" id="id5"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt>
<dd><p>A string literal appearing as the first statement in the function body is
transformed into the function’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute and therefore the
function’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
</dd>
<dt class="label" id="id6"><span class="brackets"><a class="fn-backref" href="#id3">3</a></span></dt>
<dd><p>A string literal appearing as the first statement in the class body is
transformed into the namespace’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the class’s
<a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</p>
</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8. Compound statements</a><ul>
<li><a class="reference internal" href="#the-if-statement">8.1. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li><a class="reference internal" href="#the-while-statement">8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li><a class="reference internal" href="#the-for-statement">8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-try-statement">8.4. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li><a class="reference internal" href="#the-with-statement">8.5. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#function-definitions">8.6. Function definitions</a></li>
<li><a class="reference internal" href="#class-definitions">8.7. Class definitions</a></li>
<li><a class="reference internal" href="#coroutines">8.8. Coroutines</a><ul>
<li><a class="reference internal" href="#coroutine-function-definition">8.8.1. Coroutine function definition</a></li>
<li><a class="reference internal" href="#the-async-for-statement">8.8.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-async-with-statement">8.8.3. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> statement</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="simple_stmts.html"
                        title="previous chapter"><span class="section-number">7. </span>Simple statements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="toplevel_components.html"
                        title="next chapter"><span class="section-number">9. </span>Top-level components</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.8/Doc/reference/compound_stmts.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="9. Top-level components"
             >next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="7. Simple statements"
             >previous</a> |</li>

          <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.8.13 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
                     |
                </li>
            
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2022, Python Software Foundation.
    <br />
    This page is licensed under the Python Software Foundation License Version 2.
    <br />
    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
    <br />
    
    <br />

    The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
    <br />

    Last updated on Mar 17, 2022.
    <a href="https://docs.python.org/3/bugs.html">Found a bug</a>?
    <br />

    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
    </div>

  </body>
</html>